#!/usr/bin/python
# -*- coding:utf-8 -*-
import requests
import urllib3
from Base.baseData import DataBase
from Base.baseLogger import Logger
from urllib3.exceptions import InsecureRequestWarning
from urllib.parse import urljoin

logger = Logger('baseAutoHttp.py').getLogger()


class ApiBase(DataBase):
    '''接口测试工具类'''

    session = requests.session()   #将session会话保存

    def __init__(self, yamlName):
        super().__init__(yamlName)
        self.timeout = 10   #接口的超时时间，单位秒

    def request_base(self,apiName,change_data=None,**kwargs):
        '''接口请求公共封装'''
        try:
            logger.info('【{}:{}接口调用开始】'.format(self.yamlName,apiName))
            yaml_data = self.get_element_data(change_data)[apiName]
            yaml_data['url'] = urljoin(self.run_config['TEST_URL'],yaml_data['url'])
            logger.info('获取【{}】文件【{}】接口请求数据：{}'.format(self.yamlName,apiName,yaml_data))
            logger.info('接口的请求方式：{}'.format(yaml_data['method']))
            logger.info('接口的请求地址：{}'.format(yaml_data['url']))
            if 'data' in yaml_data.keys():
                logger.info('接口的请求体：{}'.format(yaml_data['data']))
            elif 'json' in yaml_data.keys():
                logger.info('接口的请求体：{}'.format(yaml_data['json']))
            urllib3.disable_warnings(InsecureRequestWarning)
            res = ApiBase.session.request(**yaml_data,**kwargs)
            logger.info('接口的响应时间：{}'.format(res.elapsed.total_seconds()))
            logger.debug('POST-接口的响应码：{}'.format(res.status_code))
            logger.debug('POST-接口的响应体：{}'.format(res.text))
            logger.info('【{}:{}接口调用结束】'.format(self.yamlName,apiName))
            return res
        except Exception as e:
            logger.error('接口请求失败！：{}'.format(e))
            raise e


if __name__ == '__main__':
    change_data = {
        "Authorization": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoidXNlciIsImlkIjoicm9vdCIsIm5hbWUiOiLotoXnuqfnrqHnkIblkZgiLCJjb25zdW1lciI6IkJJVC1NU0EiLCJ0ZW5hbnRJZCI6ImFkbWluIiwic2VjcmV0X2lkIjoiMkVGQ0Q4QTE5Q0YwNDZEQjg2NUFCMjIyNzg1NkQ4NDEiLCJpc3MiOiJCSVQtTVNBIiwiaWF0IjoxNjU2MTYxNDc2LCJuYmYiOjE2NTYxNjE0NzYsImV4cCI6MTY1NjE2ODk3Nn0.q8y0j_VF2o2L_HEKOuA47o5VDwqnHxxuclJjQsAFlSw",
        "name":"自动化",
        "describe":"测试"
    }
    res = ApiBase('接口元素信息')
    res1 = res.request_base('vipinsert',change_data)
    print(res1.json())

    res2 = res.request_base('vipselect', change_data)
    print(res2.json()['result']['rows'][0]['rosterName'])

    res3 = res.request_base('vipselectzdh', change_data)
    print(res3.json())
